# custom_db_backend/base.py

import pymysql
from dbutils.pooled_db import PooledDB
from django.db.backends.mysql.base import DatabaseWrapper as MySQLDatabaseWrapper

# 自定义连接类，修复 autocommit 缺失问题
class PatchedSteadyDBConnection:
    def __init__(self, pooled_conn):
        self._pooled_conn = pooled_conn

    def __getattr__(self, name):
        # 代理所有属性和方法到底层 SteadyDBConnection
        return getattr(self._pooled_conn, name)

    def autocommit(self, mode):
        # 显式实现 autocommit 方法
        self._pooled_conn.autocommit(mode)

# 创建连接池
POOL = PooledDB(
    creator=pymysql,
    maxconnections=500,
    mincached=10,
    maxcached=50,
    blocking=True,
    host='127.0.0.1',
    user='root',
    password='123456',
    database='seckill_py',
    charset='utf8mb4',
    port=3306,
    autocommit=True  # 关键：初始化时启用自动提交
)

def get_connection():
    # 返回修补后的连接对象
    raw_conn = POOL.connection()
    return PatchedSteadyDBConnection(raw_conn)

class DatabaseWrapper(MySQLDatabaseWrapper):
    def get_new_connection(self, conn_params):
        return get_connection()

    def _set_autocommit(self, autocommit):
        # 使用修补后的 autocommit 方法
        self.connection.autocommit(autocommit)